package com.guomao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;


@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();

        // 检查用户是否已登录
        if (session.getAttribute("username") != null) {
            PrintWriter pw = response.getWriter();
            // 用户已登录，显示欢迎信息
            session.getAttribute("username");
            response.sendRedirect("logout.jsp");
        } else {
            // 检查是否有记住的用户名Cookie
            Cookie[] cookies = request.getCookies();
            String rememberedUsername = null;
            String rememberedPassword = null;

            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("rememberedUsername".equals(cookie.getName())) {
                        rememberedUsername = cookie.getValue();
                    }
                    if ("rememberedPassword".equals(cookie.getName())) {
                        rememberedPassword = cookie.getValue();
                    }
                }
            }

            // 如果有记住的用户名，自动填充登录表单
            if (rememberedUsername != null && rememberedPassword != null) {
                response.sendRedirect("login.html?username=" +
                        URLEncoder.encode(rememberedUsername, "UTF-8") +
                        "&password=" + URLEncoder.encode(rememberedPassword, "UTF-8"));
            } else {
                // 否则重定向到登录页面
                response.sendRedirect("login.jsp");
            }
        }
    }
}